<template>
  <view class="income-add-container">
    <view class="page-header">
      <text class="page-title">新增收入记录</text>
      <text class="page-subtitle">录入员工收入信息</text>
    </view>

    <view class="form-container">
      <view class="form-section">
        <text class="section-title">基本信息</text>
        
        <view class="form-item">
          <text class="form-label required">选择员工</text>
          <picker 
            mode="selector" 
            :range="userList" 
            range-key="displayName"
            :value="selectedUserIndex"
            @change="onUserChange"
          >
            <view class="picker-view">
              <text class="picker-text">{{ selectedUserName || '请选择员工' }}</text>
            </view>
          </picker>
          <text v-if="errors.user_id" class="error-text">{{ errors.user_id }}</text>
        </view>

        <view class="form-item">
          <text class="form-label required">所属月份</text>
          <picker mode="date" fields="month" :value="formData.year_month" @change="onMonthChange">
            <view class="picker-view">
              <text class="picker-text">{{ formData.year_month || '请选择月份' }}</text>
            </view>
          </picker>
          <text v-if="errors.year_month" class="error-text">{{ errors.year_month }}</text>
        </view>
      </view>

      <view class="form-section">
        <text class="section-title">收入明细</text>
        
        <view class="form-item">
          <text class="form-label required">基本工资（元）</text>
          <uni-easyinput 
            v-model="formData.base_salary"
            type="number"
            placeholder="请输入基本工资"
            :clearable="true"
            @input="calculateTotal"
          />
        </view>

        <view class="form-item">
          <text class="form-label">提成金额（元）</text>
          <uni-easyinput 
            v-model="formData.commission_amount"
            type="number"
            placeholder="请输入提成金额"
            :clearable="true"
            @input="calculateTotal"
          />
        </view>

        <view class="form-item">
          <text class="form-label">奖金（元）</text>
          <uni-easyinput 
            v-model="formData.bonus_amount"
            type="number"
            placeholder="请输入奖金"
            :clearable="true"
            @input="calculateTotal"
          />
        </view>

        <view class="form-item">
          <text class="form-label">扣款（元）</text>
          <uni-easyinput 
            v-model="formData.deduction_amount"
            type="number"
            placeholder="请输入扣款金额"
            :clearable="true"
            @input="calculateTotal"
          />
        </view>

        <view class="form-item">
          <text class="form-label">分红（元）</text>
          <uni-easyinput 
            v-model="formData.dividend_amount"
            type="number"
            placeholder="请输入分红金额"
            :clearable="true"
            @input="calculateTotal"
          />
        </view>

        <view class="form-item">
          <text class="form-label">总收入（元）</text>
          <view class="calculated-value">
            <text class="value-text">¥{{ totalIncome }}</text>
          </view>
          <text class="form-hint">自动计算：基本工资 + 提成 + 奖金 - 扣款 + 分红</text>
        </view>
      </view>

      <view class="form-section">
        <text class="section-title">其他信息</text>
        
        <view class="form-item">
          <text class="form-label">备注</text>
          <textarea 
            v-model="formData.remarks" 
            class="form-textarea" 
            placeholder="请输入备注信息（选填）"
            maxlength="500"
          />
        </view>

        <view class="form-item">
          <text class="form-label required">状态</text>
          <radio-group @change="onStatusChange" class="radio-group">
            <label class="radio-item">
              <radio value="1" :checked="formData.status === 1" color="#007aff"/>
              <text class="radio-text">草稿</text>
            </label>
            <label class="radio-item">
              <radio value="2" :checked="formData.status === 2" color="#007aff"/>
              <text class="radio-text">已审批</text>
            </label>
            <label class="radio-item">
              <radio value="3" :checked="formData.status === 3" color="#007aff"/>
              <text class="radio-text">已发放</text>
            </label>
          </radio-group>
        </view>
      </view>

      <view class="form-actions">
        <button class="btn btn-cancel" @click="handleCancel">取消</button>
        <button class="btn btn-primary" @click="handleSubmit">提交</button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'

// 员工列表相关
const userList = ref([])
const selectedUserIndex = ref(-1)
const selectedUserName = ref('')

const formData = reactive({
  user_id: '',
  year_month: '',
  base_salary: '',
  commission_amount: '',
  bonus_amount: '',
  deduction_amount: '',
  dividend_amount: '',
  total_income: 0,
  remarks: '',
  created_by: 'admin',
  status: 1
})

const errors = reactive({
  user_id: '',
  year_month: ''
})

// 页面加载时获取员工列表
onMounted(async () => {
  await loadUserList()
})

const totalIncome = computed(() => {
  const base = parseFloat(formData.base_salary) || 0
  const commission = parseFloat(formData.commission_amount) || 0
  const bonus = parseFloat(formData.bonus_amount) || 0
  const deduction = parseFloat(formData.deduction_amount) || 0
  const dividend = parseFloat(formData.dividend_amount) || 0
  const total = base + commission + bonus - deduction + dividend
  formData.total_income = total
  return total.toFixed(2)
})

// 加载员工列表
async function loadUserList() {
  try {
    uni.showLoading({ title: '加载员工列表...' })
    
    // 调用云对象方法查询员工列表（所有员工，排除患者）
    const userQueryObj = uniCloud.importObject('dh-user-query')
    const result = await userQueryObj.listStaff('with_role')
    
    uni.hideLoading()
    
    if (result.code === 200 && result.data) {
      // 格式化数据以匹配原有的数据结构
      userList.value = result.data.map(user => ({
        _id: user._id,
        displayName: user.displayName,
        realName: user.realName
      }))
      
      if (userList.value.length === 0) {
        uni.showToast({ title: '未找到员工', icon: 'none' })
      }
    } else {
      console.error('查询员工列表失败:', result.message)
      uni.showToast({ 
        title: result.message || '查询员工列表失败', 
        icon: 'none' 
      })
    }
  } catch (error) {
    console.error('加载员工列表失败:', error)
    uni.hideLoading()
    uni.showToast({ title: '加载员工列表失败', icon: 'none' })
  }
}

// 员工选择改变
function onUserChange(e) {
  const index = e.detail.value
  selectedUserIndex.value = index
  if (index >= 0 && index < userList.value.length) {
    const selectedUser = userList.value[index]
    formData.user_id = selectedUser._id
    selectedUserName.value = selectedUser.displayName
    errors.user_id = ''
  }
}

function onMonthChange(e) {
  const value = e.detail.value
  if (value) {
    const parts = value.split('-')
    formData.year_month = `${parts[0]}-${parts[1]}`
  }
  errors.year_month = ''
}

function onStatusChange(e) {
  formData.status = parseInt(e.detail.value)
}

function calculateTotal() {
  // 触发computed重新计算
}

function validateForm() {
  let isValid = true
  
  if (!formData.user_id || formData.user_id.trim().length === 0) {
    errors.user_id = '请选择员工'
    isValid = false
  } else {
    errors.user_id = ''
  }
  
  if (!formData.year_month) {
    errors.year_month = '请选择所属月份'
    isValid = false
  } else {
    errors.year_month = ''
  }
  
  return isValid
}

async function handleSubmit() {
  if (!validateForm()) {
    uni.showToast({ title: '请检查表单错误', icon: 'none' })
    return
  }
  
  try {
    uni.showLoading({ title: '提交中...' })
    
    const submitData = {
      ...formData,
      base_salary: parseFloat(formData.base_salary) || 0,
      commission_amount: parseFloat(formData.commission_amount) || 0,
      bonus_amount: parseFloat(formData.bonus_amount) || 0,
      deduction_amount: parseFloat(formData.deduction_amount) || 0,
      dividend_amount: parseFloat(formData.dividend_amount) || 0
    }
    
    // 调用云对象方法创建收入记录（会自动挂载 hospital_id）
    const incomeRecordsObj = uniCloud.importObject('dh-income_records')
    const result = await incomeRecordsObj.createIncomeRecord(submitData)
    
    uni.hideLoading()
    
    if (result.code === 201 && result.data && result.data._id) {
      uni.showToast({ title: result.message || '创建成功', icon: 'success' })
      setTimeout(() => {
        uni.redirectTo({ url: '/pages/business/income_records/list' })
      }, 1500)
    } else {
      uni.showToast({ title: '创建失败', icon: 'none' })
    }
  } catch (err) {
    console.error('创建失败:', err)
    uni.hideLoading()
    uni.showToast({ title: err.message || '创建失败', icon: 'none' })
  }
}

function handleCancel() {
  uni.redirectTo({ url: '/pages/business/income_records/list' })
}
</script>

<style lang="scss" scoped>
.income-add-container {
  min-height: 100vh;
  background: #f5f5f5;
  padding: 20rpx;
}

.page-header {
  background: #fff;
  padding: 40rpx;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
}

.page-title {
  font-size: 44rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 12rpx;
}

.page-subtitle {
  font-size: 28rpx;
  color: #999;
  display: block;
}

.form-container {
  background: #fff;
  border-radius: 16rpx;
  overflow: hidden;
}

.form-section {
  padding: 40rpx;
  border-bottom: 1rpx solid #f0f0f0;
  
  &:last-child {
    border-bottom: none;
  }
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 30rpx;
  padding-bottom: 16rpx;
  border-bottom: 2rpx solid #007aff;
}

.form-item {
  margin-bottom: 32rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.form-label {
  font-size: 28rpx;
  color: #666;
  display: block;
  margin-bottom: 16rpx;
  
  &.required::after {
    content: ' *';
    color: #ff3b30;
  }
}

.form-hint {
  font-size: 24rpx;
  color: #999;
  display: block;
  margin-top: 8rpx;
}

.picker-view {
  padding: 20rpx;
  background: #fafafa;
  border: 1rpx solid #e0e0e0;
  border-radius: 8rpx;
}

.picker-text {
  font-size: 28rpx;
  color: #333;
}

.calculated-value {
  padding: 24rpx;
  background: #e8f5e9;
  border-radius: 8rpx;
  text-align: center;
}

.value-text {
  font-size: 48rpx;
  font-weight: bold;
  color: #2e7d32;
}

.form-textarea {
  width: 100%;
  min-height: 160rpx;
  padding: 20rpx;
  font-size: 28rpx;
  border: 1rpx solid #e0e0e0;
  border-radius: 8rpx;
  box-sizing: border-box;
  background: #fafafa;
}

.radio-group {
  display: flex;
  flex-wrap: wrap;
  gap: 24rpx;
}

.radio-item {
  display: flex;
  align-items: center;
  padding: 16rpx 24rpx;
  background: #fafafa;
  border-radius: 8rpx;
  border: 1rpx solid #e0e0e0;
}

.radio-text {
  font-size: 28rpx;
  color: #333;
  margin-left: 12rpx;
}

.error-text {
  font-size: 24rpx;
  color: #ff3b30;
  display: block;
  margin-top: 8rpx;
}

.form-actions {
  display: flex;
  gap: 20rpx;
  padding: 30rpx 40rpx;
  background: #fff;
  border-top: 1rpx solid #f0f0f0;
}

.btn {
  flex: 1;
  height: 88rpx;
  line-height: 88rpx;
  text-align: center;
  font-size: 32rpx;
  border-radius: 12rpx;
  border: none;
  
  &.btn-cancel {
    background: #f5f5f5;
    color: #666;
  }
  
  &.btn-primary {
    background: #007aff;
    color: #fff;
  }
}
</style>
